<template>
	<div class="modal" v-on:keyup.esc="dismiss" v-show="show">
		<div class="modal-dialog">
			<div class="modal-content">
				<input class="search-bar" type="text" v-bind:placeholder="expendHint" v-if="!isIncome" v-model="userInput" v-on:keyup.enter="onEnter">
				<input class="search-bar" type="text" v-bind:placeholder="incomeHint" v-if="isIncome" v-model="userInput" v-on:keyup.enter="onEnter">
				<a href="#" class="go-icon" v-on:click="onEnter">
					<svg width="24" height="24" viewBox="0 0 24 24">
						<path d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z"></path>
					</svg>
				</a>
			</div>
		</div>
	</div>
</template>

<script>
import {bus} from '../main.js'

export default{
	name: 'addmodal',
	data() {
		return {
			userInput: '',
			show: false,
			isIncome: false,
			expendHint: '用空格来分隔支出用途和金额。如: 看电影 80.5',
			incomeHint: '用空格来分隔收入来源和金额。如: 稿费 500.5'
		}
	},
	methods: {
		onEnter: function(){
			let splited = this.userInput.split(' ')
			if(splited.length != 2){
				bus.$emit('alert', '输入格式不对！')
				this.show = false
				return undefined
			}
			let purpose = splited[0]
			let amount = parseFloat(splited[1])
			if(isNaN(amount)){
				bus.$emit('alert', '请输入数字！')
				this.show = false
				return undefined
			}

			if(amount < 0){
				bus.$emit('alert', '不要输入负号。')
				this.show = false
				return undefined
			}

			if(!this.isIncome){
				amount = -amount
			}
			let timeStamp = new Date().getTime()
			let accountID = window.delegate.addAccount({
				purpose: purpose,
				amount: amount,
				timeStamp: timeStamp
			})
			bus.$emit('did_add_account', accountID - 1)
			this.show = false
		},

		dismiss: function(){
			this.show = false;
		}, 
	},
	mounted: function(){
		bus.$on('show_add_modal', function(isIncome){
			this.isIncome = isIncome
			this.show = true
		}.bind(this))		
	}
}
</script>

<style scoped>

.modal{
	background-color: rgba(133,133,133,0.3);
	position: fixed;
	top: 0px;
	bottom: 0px;
	left: 0px;
	right: 0px;
	outline: 0;
	z-index: 1050;
	opacity: 1;
	box-sizing: border-box;
}

.modal-dialog{
	margin: 300px auto;
	position: relative;
	width: 70%;
}

.search-bar{
	width: 100%;
	height: 50px;
	border-radius: 5px;
	font-size: 24px;
	padding-left: 15px;
	background: white;
	border: 3px solid darkred;
	opacity: 1;
	outline: none;
	color: darkred; 
	text-shadow: 0px 0px 0px black; 
	-webkit-text-fill-color: transparent;
}

.go-icon{
	float: right;
	position: relative;
	top: -40px;
}

</style>